<template>
  <div class="trade-users-detail">
    <el-card>
      <!-- 页面标题 -->
      <div style="display: flex; align-items: center; margin-bottom: 20px;">
        <el-button @click="goBack" style="margin-right: 12px;">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <h3 style="margin: 0;">绑定用户详情</h3>
      </div>

      <!-- 交易账号信息 -->
      <div v-if="tradeAccount" style="margin-bottom: 20px; padding: 16px; background-color: #f8f9fa; border-radius: 4px;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;">
          <div>
            <strong>交易账号：</strong>{{ tradeAccount.account }}
          </div>
          <el-tag type="primary">{{ tradeAccount.bindUsers?.length || 0 }} 个绑定用户</el-tag>
        </div>
        <div style="color: #666; font-size: 14px;">
          <div><strong>站点：</strong>{{ tradeAccount.site }}</div>
          <div><strong>备注：</strong>{{ tradeAccount.remark || '无' }}</div>
        </div>
      </div>

      <!-- 添加新用户 -->
      <div style="margin-bottom: 20px; padding: 16px; border: 1px solid #e4e7ed; border-radius: 4px;">
        <h4 style="margin: 0 0 12px 0; color: #333;">添加绑定用户</h4>
        <div style="margin-bottom: 12px;">
          <div style="color: #666; font-size: 12px; margin-bottom: 8px;">
            支持输入用户ID或用户昵称，可输入多个（用逗号分隔），至少填写一项
          </div>
          <div style="display: flex; gap: 12px; align-items: center;">
            <el-input
              v-model="newUserInfo.userIds"
              placeholder="请输入用户ID，多个用逗号分隔"
              style="width: 300px;"
            />
            <el-input
              v-model="newUserInfo.nicknames"
              placeholder="请输入用户昵称，多个用逗号分隔"
              style="width: 300px;"
            />
            <el-button type="primary" @click="addUsers">
              添加
            </el-button>
          </div>
        </div>
      </div>

      <!-- 绑定用户列表 -->
      <el-table :data="pagedUsers" style="width: 100%" max-height="400">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="id" label="用户ID" width="120" />
        <el-table-column prop="nickname" label="用户昵称" width="150" />
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button size="small" type="danger" text @click="removeUser(scope.$index)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-pagination
        v-model:current-page="page.current"
        v-model:page-size="page.size"
        :total="tradeAccount?.bindUsers?.length || 0"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 30, 50]"
        style="margin-top: 16px; text-align: right;"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()

// 交易账号数据
const tradeAccount = ref<any>(null)

// 新用户信息
const newUserInfo = ref({
  userIds: '',
  nicknames: ''
})

// 分页相关
const page = ref({
  current: 1,
  size: 10
})

// 分页后的用户数据
const pagedUsers = computed(() => {
  if (!tradeAccount.value?.bindUsers) return []
  
  const start = (page.value.current - 1) * page.value.size
  const end = start + page.value.size
  return tradeAccount.value.bindUsers.slice(start, end)
})

// 页面加载时获取交易账号数据
onMounted(() => {
  const accountId = route.params.id as string
  
  // 从mock数据中获取真实的交易账号数据
  import('@/mock/tradeAccounts').then(({ tradeAccounts }) => {
    const account = tradeAccounts.value.find(acc => acc.account === accountId)
    if (account) {
      tradeAccount.value = { ...account }
    } else {
      // 如果找不到账号，显示错误信息
      ElMessage.error('未找到对应的交易账号')
      router.back()
    }
  })
})

// 返回交易账号页面
function goBack() {
  router.push('/settings/account?tab=trade')
}

// 模拟会员数据（与员工管理页面保持一致）
const memberList = ref([
  { id: 'M001', name: '陈小明', avatar: '' },
  { id: 'M002', name: '刘美丽', avatar: '' },
  { id: 'M003', name: '王建国', avatar: '' },
  { id: 'M004', name: '张小红', avatar: '' },
  { id: 'M005', name: '李志强', avatar: '' },
  { id: 'M006', name: '赵雅琴', avatar: '' },
  { id: 'M007', name: '孙伟', avatar: '' },
  { id: 'M008', name: '周丽华', avatar: '' }
])

// 添加用户
function addUsers() {
  const userIds = newUserInfo.value.userIds.trim()
  const nicknames = newUserInfo.value.nicknames.trim()
  
  if (!userIds && !nicknames) {
    ElMessage.warning('请至少填写用户ID或用户昵称')
    return
  }
  
  const newUsers: any[] = []
  const errors: string[] = []
  const notFoundErrors: string[] = []
  
  // 处理用户ID输入
  if (userIds) {
    const userIdList = userIds.split(',').map(id => id.trim()).filter(id => id)
    for (const userId of userIdList) {
      // 检查是否在会员列表中存在
      const member = memberList.value.find(m => m.id === userId)
      if (!member) {
        notFoundErrors.push(`用户ID "${userId}" 在会员列表中不存在`)
        continue
      }
      
      // 检查重复
      const exists = tradeAccount.value.bindUsers.some((user: any) => user.id === userId)
      if (exists) {
        errors.push(`用户ID "${userId}" 已存在`)
        continue
      }
      
      // 生成昵称（如果没有提供昵称）
      const nickname = nicknames ? nicknames.split(',')[newUsers.length]?.trim() || member.name : member.name
      newUsers.push({ id: userId, nickname })
    }
  }
  
  // 处理用户昵称输入（如果只输入了昵称）
  if (!userIds && nicknames) {
    const nicknameList = nicknames.split(',').map(name => name.trim()).filter(name => name)
    for (const nickname of nicknameList) {
      // 检查是否在会员列表中存在
      const member = memberList.value.find(m => m.name === nickname)
      if (!member) {
        notFoundErrors.push(`用户昵称 "${nickname}" 在会员列表中不存在`)
        continue
      }
      
      // 检查重复
      const exists = tradeAccount.value.bindUsers.some((user: any) => user.nickname === nickname)
      if (exists) {
        errors.push(`用户昵称 "${nickname}" 已存在`)
        continue
      }
      
      newUsers.push({ id: member.id, nickname: member.name })
    }
  }
  
  // 显示错误信息
  if (notFoundErrors.length > 0) {
    ElMessage.error(`以下用户不存在：${notFoundErrors.join(', ')}`)
  }
  
  if (errors.length > 0) {
    ElMessage.warning(`以下用户已存在：${errors.join(', ')}`)
  }
  
  // 添加新用户
  if (newUsers.length > 0) {
    tradeAccount.value.bindUsers.push(...newUsers)
    
    // 同步更新mock数据
    import('@/mock/tradeAccounts').then(({ tradeAccounts }) => {
      const accountIndex = tradeAccounts.value.findIndex(acc => acc.account === tradeAccount.value.account)
      if (accountIndex !== -1) {
        tradeAccounts.value[accountIndex].bindUsers = [...tradeAccount.value.bindUsers]
      }
    })
    
    // 清空输入
    newUserInfo.value = { userIds: '', nicknames: '' }
    
    // 跳转到最后一页以显示新添加的用户
    const totalPages = Math.ceil(tradeAccount.value.bindUsers.length / page.value.size)
    if (totalPages > page.value.current) {
      page.value.current = totalPages
    }
    
    ElMessage.success(`成功添加 ${newUsers.length} 个用户`)
  }
}

// 删除用户
function removeUser(index: number) {
  ElMessageBox.confirm(
    '确定要删除这个绑定用户吗？',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 计算在原始数据中的实际索引
    const actualIndex = (page.value.current - 1) * page.value.size + index
    tradeAccount.value.bindUsers.splice(actualIndex, 1)
    
    // 同步更新mock数据
    import('@/mock/tradeAccounts').then(({ tradeAccounts }) => {
      const accountIndex = tradeAccounts.value.findIndex(acc => acc.account === tradeAccount.value.account)
      if (accountIndex !== -1) {
        tradeAccounts.value[accountIndex].bindUsers = [...tradeAccount.value.bindUsers]
      }
    })
    
    ElMessage.success('删除成功')
    
    // 如果当前页没有数据了，且不是第一页，则跳转到上一页
    if (pagedUsers.value.length === 0 && page.value.current > 1) {
      page.value.current--
    }
  }).catch(() => {
    // 用户取消删除
  })
}
</script>

<style scoped>
.trade-users-detail {
  padding: 16px;
}
</style> 